const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const asyncHandler = require('express-async-handler');

const auth = asyncHandler(async (req, res, next) => {
  let token;

  // 从请求头中获取token
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
    token = req.headers.authorization.split(' ')[1];
  }

  if (!token) {
    res.status(401);
    throw new Error('未授权访问');
  }

  try {
    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-jwt-secret');

    // 查找用户
    const user = await User.findById(decoded.id).select('-password');
    if (!user) {
      res.status(401);
      throw new Error('用户不存在');
    }

    // 将用户信息添加到请求对象中
    req.user = user;
    next();
  } catch (error) {
    res.status(401);
    throw new Error('无效的token');
  }
});

module.exports = auth;